package com.pig4cloud.pig.module.controller.charger;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig4cloud.pig.common.core.util.DateUtils;
import com.pig4cloud.pig.common.core.util.OkHttpClientUtil;
import com.pig4cloud.pig.common.core.util.QRCodeUtilEx;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.mybatis.page.PageUtils;
import com.pig4cloud.pig.common.mybatis.page.TableDataInfo;
import com.pig4cloud.pig.common.security.service.PigUser;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import com.pig4cloud.pig.module.api.entity.charger.Charger;
import com.pig4cloud.pig.module.api.entity.estate.Estate;
import com.pig4cloud.pig.module.service.charger.IChargerService;
import com.pig4cloud.pig.module.service.estate.IEstateService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 充电设备Controller
 *
 * @author ruoyi
 * @date 2022-05-07
 */
@Validated
@Api(value = "充电设备控制器", tags = {"充电设备管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/charger")
public class ChargerController {

    private final IChargerService chargerService;
	private final IEstateService estateService;

    @Resource
    protected RedisTemplate<String, Object> redisTemplate;

	@Value("${ruoyi.profile}")
	private String uploadPath;

    /**
     * 查询充电设备列表
     */
    @ApiOperation("查询充电设备列表")
    @PreAuthorize("@pms.hasPermission('module:charge:list')")
    @GetMapping("/list")
    public TableDataInfo<Charger> list(@Validated Charger charger) {
        QueryWrapper<Charger> qw = new QueryWrapper<>();
		PigUser sysUser = SecurityUtils.getUser();
		if(sysUser.getUserType() == 2){//物业公司
			qw.eq("property_id",sysUser.getPropertyId());
		} else if(sysUser.getUserType() == 3){//小区
			qw.eq("estate_id",sysUser.getEstateId());
		}
        if(charger.getEstateId() != null){
        	qw.eq("estate_id",charger.getEstateId());
		}

        if(charger.getState()!=null){
			qw.eq("state",charger.getState());
		}

		if(charger.getChargerSn()!=null){
			qw.eq("charger_sn",charger.getChargerSn());
		}
        TableDataInfo<Charger> td = PageUtils.buildDataInfo(chargerService.page(PageUtils.buildPage(),qw));
        List<Charger> list = td.getData();
        if(CollUtil.isNotEmpty(list)){
        	for(Charger charger1 : list){
				Estate estate = estateService.findById(charger1.getEstateId());
				if(estate!=null){
					charger1.setEstateName(estate.getEstateName());
				}
			}
		}
        return td;
    }

    /**
     * 导出充电设备列表
     */
    @ApiOperation("导出充电设备列表")
    @PreAuthorize("@pms.hasPermission('module:charge:export')")
    @SysLog("充电设备")
    @GetMapping("/export")
    public List export(@Validated Charger charger) {
        List<Charger> list = chargerService.list();
        // ExcelUtil<Charger> util = new // ExcelUtil<Charger>(Charger.class);
        return  list;// util.exportExcel(list, "充电设备");
    }

    /**
     * 获取充电设备详细信息
     */
    @ApiOperation("获取充电设备详细信息")
    @PreAuthorize("@pms.hasPermission('module:charge:query')")
    @GetMapping("/{id}")
    public R<Charger> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        Charger charger = chargerService.getById(id);
        if(charger!=null){
        	if(charger.getIsFree() == 1){
				String[] dateRange = {  DateUtils.getDate(charger.getFreeBeginTime()),  DateUtils.getDate(charger.getFreeEndTime()) };
				charger.setDateRange(dateRange);
			}
			String[] areas = { charger.getProv(),charger.getCity(),charger.getDistrict() };
			charger.setProvinceArray(areas);
		}
        return R.ok(charger);
    }


	/**
	 * 重置二维码
	 */
	@SysLog("重置二维码")
	@PostMapping("/resetQrCode")
	@ResponseBody
	@PreAuthorize("@pms.hasPermission('module:charge:edit')")
	public R<Void> resetQrCode(@RequestBody Charger charger) {
		if(charger.getId()!=null){
			try{
				charger = chargerService.getById(charger.getId());
				if(charger!=null){
					String qrCode = "";
					String fileName = "device_qr_" + charger.getChargerSn() + ".jpg";
					String content = "https://www.sdyuedou.com/wxmini/charger/qr?sn=" + charger.getChargerSn() + "&port=1";
					int upload_type = 0;//FileUploadUtils.TYPE_CHARGER;
					System.out.println("content:  "+ content);
					String img_key = "";//FileUploadUtils.getUploadPrefix(upload_type) + fileName;
					QRCodeUtilEx.createQrCodeImg(content, "设备编号：" + charger.getChargerSn(),
						null, uploadPath +"/"+img_key, true, fileName, upload_type);
					qrCode = img_key;
					charger.setQrCode(qrCode);
				}
			}catch (Exception ex){
				ex.printStackTrace();
			}
			if (chargerService.updateById(charger)) {
				return R.ok();
			}
		}
		return R.failed();
	}

    /**
     * 新增充电设备
     */
    @ApiOperation("新增充电设备")
    @PreAuthorize("@pms.hasPermission('module:charge:add')")
    @SysLog("充电设备")

    @PostMapping()
    public R<Void> add(@Valid @RequestBody Charger charger) {
		if(charger.getDateRange()!=null&&charger.getDateRange().length==2){
			String[] dateRange = charger.getDateRange();
			Date freeBeginTime = DateUtils.parseDate( dateRange[0] + " 00:00:00");
			Date freeEndTime = DateUtils.parseDate( dateRange[1] + " 23:59:59");
			charger.setFreeBeginTime(freeBeginTime);
			charger.setFreeEndTime(freeEndTime);
		}
		if(charger.getProvinceArray()!=null&&charger.getProvinceArray().length==3){
			charger.setProv(charger.getProvinceArray()[0]);
			charger.setCity(charger.getProvinceArray()[1]);
			charger.setDistrict(charger.getProvinceArray()[2]);
		}
        return R.okByRow(chargerService.save(charger) ? 1 : 0);
    }

    /**
     * 修改充电设备
     */
    @ApiOperation("修改充电设备")
    @PreAuthorize("@pms.hasPermission('module:charge:edit')")
    @SysLog("充电设备")

    @PutMapping()
    public R<Void> edit(@Valid @RequestBody Charger charger) {
    	if(charger.getDateRange()!=null){
			String[] dateRange = charger.getDateRange();
			Date freeBeginTime = DateUtils.parseDate( dateRange[0] + " 00:00:00");
			Date freeEndTime = DateUtils.parseDate( dateRange[1] + " 23:59:59");
			charger.setFreeBeginTime(freeBeginTime);
			charger.setFreeEndTime(freeEndTime);
		}
		if(charger.getProvinceArray()!=null&&charger.getProvinceArray().length==3){
			charger.setProv(charger.getProvinceArray()[0]);
			charger.setCity(charger.getProvinceArray()[1]);
			charger.setDistrict(charger.getProvinceArray()[2]);
		}
    	boolean bl = chargerService.updateById(charger);
    	if(bl){
            OkHttpClientUtil.getInstance().getData("https://www.sdyuedou.com/capi/charger/reset/redis/" + charger.getId());
        }
        return R.okByRow(bl ? 1 : 0);
    }

    /**
     * 删除充电设备
     */
    @ApiOperation("删除充电设备")
    @PreAuthorize("@pms.hasPermission('module:charge:remove')")
    @SysLog("充电设备")
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Long[] ids) {
        return R.okByRow(chargerService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
